<?php

namespace app\admin\controller\personal;

use app\common\controller\Backend;
use app\admin\model\finance\FinanceLog;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 用户余额明细操作日志
 *
 * @icon fa fa-circle-o
 */
class AccountLog extends Backend
{
    
    /**
     * AccountLog模型对象
     * @var \app\admin\model\AccountLog
     */
    protected $model = null;
    protected $personal_model = null;
    protected $noNeedRight = ['addAccountLog','typeList'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\personal\AccountLog;
        $this->personal_model = new \app\admin\model\personal\Personal();

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $uid = $this->request->get('uid');
        
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('uid',$uid)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加日志明细
     */
    public function addAccountLog($uid, $money, $type, $content, $status, $arrivaltime,$form=1)
    {
        $data = [
            'uid'       => $uid,
            'log_sn'    => date('YmdHis') . rand(10000000,99999999),
            'money'     => $money,
            'type'      => $type,
            'content'   => $content,
            'status'    => $status,
            'createtime'=> time(),
            'arrivaltime'=> $arrivaltime?:time(),
            'form'       => $form,
        ];
        $result = $this->model->allowField(true)->save($data);
        return $result;
    }


    /**
     * 添加
     */
    public function add()
    {
        $uid = $this->request->get('uid');
        // dump($uid);exit;
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // dump($params);
                    $uinfo = $this->personal_model->where(['id'=>$params['uid']])->field('balance,jy_balance')->find();
                    // dump($uinfo);exit;
                    if($params['set'] == 1){
                        //增加余额
                        $result = $this->addAccountLog($params['uid'], '+'.$params['money'], 6, $params['content'], 1,'');
                        if($result){
                            $this->personal_model->where('id','=',$params['uid'])->setInc( 'balance', $params['money'] );
                        }
                    }else{
                        //减少余额
                        $result = $this->addAccountLog($params['uid'], '-'.$params['money'], 6, $params['content'], 1,'');
                        if($result){
                            $this->personal_model->where('id','=',$params['uid'])->setDec( 'balance', $params['money'] );
                        }
                    }
                    $uinfo_after = $this->personal_model->where(['id'=>$params['uid']])->field('balance,jy_balance')->find();
                    // dump($uinfo);
                    $financelog = new FinanceLog();
                    $res = $financelog->addFinanceLog($params['uid'],'后台增减余额',$uinfo['balance'],$uinfo['jy_balance'], $params['money'], $uinfo_after['balance'],$uinfo_after['jy_balance'], $params['content']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($res !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("uid", $uid);
        return $this->view->fetch();
    }

    /**
     * 明细类别
     */
    public function typeList(){
        // {if $vo.type == 1}消费{elseif $vo.type == 2/}售得{elseif $vo.type == 3/}充值{elseif $vo.type == 4/}提现{elseif $vo.type == 5/}取消订单{elseif $vo.type == 6/}后台加减{elseif $vo.type == 7/}解冻{/if}
        $list = [1=>'消费', 2=>'售得', 3=>'充值', 4=>'提现', 5=>'取消订单', 6=>'后台加减'];
        return json($list);
    }

    /**
     * 售得延迟到账金额提前到账
     */
    public function early($ids){
        $ids = $ids ? $ids : $this->request->get("ids");
        if ($ids) {
            //查询是否已操作
            $row = $this->model->get($ids);
            //已到账请勿重复操作 只执行交易中的
            if($row['status'] == 0){
                //改变明细状态及到账时间
                $data['arrivaltime'] = time();
                $data['status'] = 1;
                $result = $row->allowField(true)->save($data);
                if($result !== false){
                    //增加前用户账户信息
                    $uinfo = $this->personal_model->where(['id'=>$row['uid']])->field('balance,jy_balance')->find();
                    //用户余额增加
                    $this->personal_model->where('id','=',$row['uid'])->setInc( 'balance', $row['money'] );
                    //增加后用户账户信息
                    $uinfo_after = $this->personal_model->where(['id'=>$row['uid']])->field('balance,jy_balance')->find();
                    // dump($uinfo);
                    $financelog = new FinanceLog();
                    $financelog->addFinanceLog($row['uid'],'提前到账',$uinfo['balance'],$uinfo['jy_balance'], $row['money'], $uinfo_after['balance'],$uinfo_after['jy_balance'], '');
                    $this->success();
                }else{
                    $this->error('已到账，请勿重复操作');
                }
            }else{
                $this->error('已到账，请勿重复操作');
            }
        }else{
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
    }

}
